import { orderBy } from 'lodash'
import React, { useState } from 'react'

// 排序 hook
export const useSortTable = (data: any[]) => {
  const [sortConfig, setSortConfig] = useState<any | null>(null)

  const sortedData = React.useMemo(() => {
    if (!sortConfig) return [...data]

    return orderBy(
      data,
      [sortConfig.key],
      [sortConfig.direction],
    )
  }, [data, sortConfig])

  const requestSort = (key: string) => {
    let direction: 'asc' | 'desc' = 'asc'
    if (sortConfig && sortConfig.direction === 'asc') {
      direction = 'desc'
    }
    setSortConfig({ key, direction })
  }

  return { sortedData, requestSort, sortConfig }
}
